package com.nmgydy.util;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class JsapiUtil {

	private static String ticketKey = "wx_jsapi_ticket";

	public static String getJsapiTicket(){
		String JsapiTicket = (String) CacheUtil.get(ticketKey);
		if(JsapiTicket == null){
			System.out.println("requestJsapiTicket");
			JsapiTicket = requestJsapiTicket();
		}
		return JsapiTicket;
	}

	private static synchronized String requestJsapiTicket(){
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
		Map<String,String> params = new HashMap<String, String>();
		params.put("access_token", AccessTokenUtil.getAccessToken());
		params.put("type", "jsapi");
		try {
			HttpClientResponse res = HttpsClient.get(url,params);
			JSONObject obj = res.asJSONObject();
			if(obj != null){
				String JsapiTicket = obj.getString("ticket");
				int expireTime = obj.getIntValue("expires_in");
				CacheUtil.put(ticketKey, JsapiTicket, expireTime);
				return JsapiTicket;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getSignature(String url,String noncestr,String timestamp){
		Map<String,String> params = new TreeMap<String, String>();
		params.put("jsapi_ticket", getJsapiTicket());
		params.put("noncestr", noncestr);
		params.put("timestamp", timestamp);
		params.put("url", url);
		//System.out.println(JSON.toJSONString(params));
		StringBuffer sb = new StringBuffer();
		for(String mapKey : params.keySet()){
			sb.append(mapKey);
			sb.append('=');
			sb.append(params.get(mapKey));
			sb.append('&');
		}
		sb.deleteCharAt(sb.length()-1);

		String signature = SHA1Util.encode(sb.toString());
		return signature;
	}

	public static Attachment getMediaUrl(String mediaId){
		String accessToken = AccessTokenUtil.getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+accessToken+"&media_id="+mediaId;
		try {
			Attachment attachment = HttpsClient.downloadHttps(url);
			//JSONObject obj = res.asJSONObject();
			return attachment;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		//System.out.println(getJsapiTicket());
		//System.out.println(getJsapiTicket());
		//System.out.println(getSignature("1","1","1"));
		//String mediaUrl = getMediaUrl("F54Rk2TTMN1G1yyLBT7dRcSCvPQCVCLXks_SEHTwmP4KLLhOlxS5yWjaTCDJgM6D");
	}
}
